# calculate inhomogeneous K function
# 
# Author: guochun
###############################################################################


inhomK=function(modelingObject,r){
	modelingObject1=modelingObject
	modelingObject1@pvalue=FALSE
	fittedModel=agModeling.poissonM(modelingObject1)
	fittedModel@pvalue=modelingObject@pvalue
	#estimate density and location density
	#lambda=predict(attr(fittedModel,"re.ppm"),locations=attr(fittedModel,"data.ppp"), type="trend")
	lambda=predict(attr(fittedModel,"re.ppm"), type="trend",ngrid=dim(modelingObject@covr[[1]])[1])
	#lambda=predict(attr(fittedModel,"re.ppm"), type="trend")
	# caculate inhomogeneous K function
	K=Kinhom(attr(fittedModel,"data.ppp"),lambda,correction="isotropic",nlarge=5000,
			r=r)
	#whichmax=which(is.nan(K$border))
	#if(length(whichmax)!=0)
	#	rmax=K$r[min(whichmax)-1]
	#else
	#	rmax=max(K$r)
	attr(fittedModel,"K")=K
	rmax=max(K$r,na.rm=T)
	#bestr=min(modelingObject@population@plotdim)/4
	#bestr=100
	#if(rmax>bestr)
	#	rmax=bestr
	attr(fittedModel,"rmax")=rmax
	return(fittedModel)
}
